package jnpf.service.impl;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import jnpf.util.UserProvider;

import jnpf.base.ActionResult;
import jnpf.entity.*;
import jnpf.mapper.ThemeMapper;
import jnpf.model.page.MyPageListVO;
import jnpf.model.page.MyPageInfo;
import jnpf.model.znm.theme.tree.TreeVO;
import jnpf.permission.service.UserService;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.theme.*;
import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;
import jnpf.model.QueryModel;

import java.math.BigDecimal;
import java.util.stream.Collectors;

import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jnpf.util.*;

import java.util.*;

import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;

/**
 * theme
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-05-08
 */
@Service
public class ThemeServiceImpl extends ServiceImpl<ThemeMapper, ThemeEntity> implements ThemeService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private ThemeTreeService themeTreeService;

    @Autowired
    private UserService userService;
    @Autowired
    private ThemeFileService themeFileService;

    @Override
    public List<ThemeEntity> getList(ThemePagination themePagination) {
        return getTypeList(themePagination, themePagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<ThemeEntity> getTypeList(ThemePagination themePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? ThemeConstant.getAppColumnData() : ThemeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total = 0;
        int themeNum = 0;
        QueryWrapper<ThemeEntity> themeQueryWrapper = new QueryWrapper<>();
        int themeTreeNum = 0;
        QueryWrapper<ThemeTreeEntity> themeTreeQueryWrapper = new QueryWrapper<>();
        long themeTreecount = themeTreeService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(themePagination.getSuperQueryJson())) {
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            String queryJson = themePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<ThemeEntity> themeSuperWrapper = new QueryWrapper<>();
            themeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(themeSuperWrapper, ThemeEntity.class, queryJson, "0"));
            int themeNum1 = themeSuperWrapper.getExpression().getNormal().size();
            if (themeNum1 > 0) {
                List<String> themeList = this.list(themeSuperWrapper).stream().map(ThemeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(themeList);
                intersectionSuperList.add(themeList);
                superNum++;
            }
            String themeTreeTable = "theme_tree";
            boolean themeTreeHasSql = queryJson.contains(themeTreeTable);
            List<String> themeTreeList = generaterSwapUtil.selectIdsByChildCondition(ThemeConstant.getTableList(), themeTreeTable, queryJson, null);
            if (themeTreeHasSql) {
                allSuperList.addAll(themeTreeList);
                intersectionSuperList.add(themeTreeList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if (superOp.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp = "";
        if (ObjectUtil.isNotEmpty(ruleJson)) {
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<ThemeEntity> themeSuperWrapper = new QueryWrapper<>();
            themeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(themeSuperWrapper, ThemeEntity.class, ruleJson, "0"));
            int themeNum1 = themeSuperWrapper.getExpression().getNormal().size();
            if (themeNum1 > 0) {
                // 添加 version 不为空的条件
                themeSuperWrapper.lambda().isNotNull(ThemeEntity::getVersion);
                List<String> themeList = this.list(themeSuperWrapper).stream().map(ThemeEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(themeList);
                intersectionRuleList.add(themeList);
                ruleNum++;
            }
            String themeTreeTable = "theme_tree";
            boolean themeTreeHasSql = ruleJson.contains(themeTreeTable);
            List<String> themeTreeList = generaterSwapUtil.selectIdsByChildCondition(ThemeConstant.getTableList(), themeTreeTable, ruleJson, null);
            if (themeTreeHasSql) {
                allRuleList.addAll(themeTreeList);
                intersectionRuleList.add(themeTreeList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if (ruleOp.equalsIgnoreCase("and")) {
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            } else {
                allRuleIDlist = allRuleList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object themeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeQueryWrapper, ThemeEntity.class, themePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(themeObj)) {
                    return new ArrayList<>();
                } else {
                    themeQueryWrapper = (QueryWrapper<ThemeEntity>) themeObj;
                    if (themeQueryWrapper.getExpression().getNormal().size() > 0) {
                        themeNum++;
                    }
                }
                Object themeTreeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeTreeQueryWrapper, ThemeTreeEntity.class, themePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(themeTreeObj)) {
                    return new ArrayList<>();
                } else {
                    themeTreeQueryWrapper = (QueryWrapper<ThemeTreeEntity>) themeTreeObj;
                    if (themeTreeQueryWrapper.getExpression().getNormal().size() > 0) {
                        themeTreeNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object themeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeQueryWrapper, ThemeEntity.class, themePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(themeObj)) {
                    return new ArrayList<>();
                } else {
                    themeQueryWrapper = (QueryWrapper<ThemeEntity>) themeObj;
                    if (themeQueryWrapper.getExpression().getNormal().size() > 0) {
                        themeNum++;
                    }
                }


                Object themeTreeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(themeTreeQueryWrapper, ThemeTreeEntity.class, themePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(themeTreeObj)) {
                    return new ArrayList<>();
                } else {
                    themeTreeQueryWrapper = (QueryWrapper<ThemeTreeEntity>) themeTreeObj;
                    if (themeTreeQueryWrapper.getExpression().getNormal().size() > 0) {
                        themeTreeNum++;
                    }
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(themePagination.getThemename())) {
                themeNum++;

                String value = themePagination.getThemename() instanceof List ? JsonUtil.getObjectToString(themePagination.getThemename()) : String.valueOf(themePagination.getThemename());
                themeQueryWrapper.lambda().like(ThemeEntity::getThemename, value);

            }

            if (ObjectUtil.isNotEmpty(themePagination.getThemetype())) {
                themeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] themetype = JsonUtil.getJsonToBean(themePagination.getThemetype(), String[][].class);
                    for (int i = 0; i < themetype.length; i++) {
                        if (themetype[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(themetype[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> themetype = JsonUtil.getJsonToList(themePagination.getThemetype(), String.class);
                        if (themetype.size() > 0) {
                            idList.addAll(themetype);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(themePagination.getThemetype()));
                    }
                }
                themeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(ThemeEntity::getThemetype, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(themePagination.getThemestatus())) {
                themeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] themestatus = JsonUtil.getJsonToBean(themePagination.getThemestatus(), String[][].class);
                    for (int i = 0; i < themestatus.length; i++) {
                        if (themestatus[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(themestatus[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> themestatus = JsonUtil.getJsonToList(themePagination.getThemestatus(), String.class);
                        if (themestatus.size() > 0) {
                            idList.addAll(themestatus);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(themePagination.getThemestatus()));
                    }
                }
                themeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(ThemeEntity::getThemestatus, tt).or();
                    });
                });

            }

        }
        if (themeTreeNum > 0) {
            List<String> themeTreeIdList = themeTreeService.list(themeTreeQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getThemeid())).map(t -> t.getThemeid()).collect(Collectors.toList());
            long count = themeTreeService.count();
            if (count > 0) {
                intersectionList.add(themeTreeIdList);
            }
            AllIdList.addAll(themeTreeIdList);
        }
        total += themeTreeNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            themeQueryWrapper.lambda().in(ThemeEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            themeQueryWrapper.lambda().and(t -> t.in(ThemeEntity::getId, finalAllSuperIDlist));
        }
        //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)) {
            if (allRuleIDlist.size() == 0) {
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            themeQueryWrapper.lambda().and(t -> t.in(ThemeEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if (StringUtil.isEmpty(themePagination.getSidx())) {
            themeQueryWrapper.lambda().orderByDesc(ThemeEntity::getId);
        } else {
            try {
                String sidx = themePagination.getSidx();
                String[] strs = sidx.split("_name");
                ThemeEntity themeEntity = new ThemeEntity();
                Field declaredField = themeEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                themeQueryWrapper = "asc".equals(themePagination.getSort().toLowerCase()) ? themeQueryWrapper.orderByAsc(value) : themeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ThemeEntity> page = new Page<>(themePagination.getCurrentPage(), themePagination.getPageSize());
                IPage<ThemeEntity> userIPage = this.page(page, themeQueryWrapper);
                return themePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ThemeEntity> list = new ArrayList();
                return themePagination.setData(list, list.size());
            }
        } else {
            return this.list(themeQueryWrapper);
        }
    }

    @Override
    public ThemeEntity getInfo(String id) {
        QueryWrapper<ThemeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ThemeEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ThemeEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ThemeEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ThemeEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * ThemeTree子表方法
     */
    @Override
    public List<ThemeTreeEntity> getThemeTreeList(String id, ThemePagination themePagination) {
        Map<String, Object> newtabMap = ThemeConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "themeTree";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<ThemeTreeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = themeTreeService.getChild(themePagination, queryWrapper);
        queryWrapper.lambda().eq(ThemeTreeEntity::getThemeid, id);
        generaterSwapUtil.wrapperHandle(ThemeConstant.getColumnData(), ThemeConstant.getAppColumnData(), queryWrapper, ThemeTreeEntity.class, "sub", tableName);
        return themeTreeService.list(queryWrapper);
    }

    /**
     * ThemeTree子表方法
     */
    @Override
    public List<ThemeTreeEntity> getThemeTreeList(String id,String isPublish) {
        QueryWrapper<ThemeTreeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ThemeTreeEntity::getThemeid, id);

        if(isPublish.equals("1")){
            // 查询已发版内容(状态为1)和已有删除(状态为3)
            queryWrapper.lambda().and(wrapper ->
                wrapper.eq(ThemeTreeEntity::getPublish, "1")
                       .or()
                       .eq(ThemeTreeEntity::getPublish, "2")
                        .or()
                       .eq(ThemeTreeEntity::getPublish, "3")
            );
        } else if(isPublish.equals("0")){
            // 查询草稿内容(状态为0)和已有编辑(状态为20)
            queryWrapper.lambda().and(wrapper ->
                wrapper.eq(ThemeTreeEntity::getPublish, "0")
                       .or()
                       .eq(ThemeTreeEntity::getPublish, "1")
                        .or()
                        .eq(ThemeTreeEntity::getPublish, "20")
            );
        }

        List<ThemeTreeEntity> result = themeTreeService.list(queryWrapper);

        // 处理状态为20的记录，使用draft作为name
        if(isPublish.equals("0")){
            result.forEach(entity -> {
                if("20".equals(entity.getPublish()) && StringUtil.isNotEmpty(entity.getDraft())){
                    entity.setName(entity.getDraft());
                }
            });
        }

        return result;
    }



    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(ThemeForm form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        //主表字段验证
        if (StringUtil.isEmpty(form.getThemename())) {
            return "主题名称不能为空";
        }
        if (StringUtil.isNotEmpty(form.getThemename())) {
            form.setThemename(form.getThemename().trim());
            QueryWrapper<ThemeEntity> themenameWrapper = new QueryWrapper<>();
            themenameWrapper.lambda().eq(ThemeEntity::getThemename, form.getThemename());
            if (isUp) {
                themenameWrapper.lambda().ne(ThemeEntity::getId, id);
            }
            if ((int) this.count(themenameWrapper) > 0) {
                countRecover = "主题名称不能重复";
            }
        }
        //子表字段验证
        if (form.getThemeTreeList() != null) {
        }
        return countRecover;
    }

    /**
     * 新增修改数据(事务回滚)
     *
     * @param id
     * @param themeForm
     * @return
     */
    @Override
    @Transactional
    public void saveOrUpdate(ThemeForm themeForm, String id, boolean isSave) throws Exception {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        themeForm = JsonUtil.getJsonToBean(generaterSwapUtil.swapDatetime(ThemeConstant.getFormData(), themeForm), ThemeForm.class);
        ThemeEntity entity = JsonUtil.getJsonToBean(themeForm, ThemeEntity.class);

        if (isSave) {
            String mainId = RandomUtil.uuId();
            entity.setCreatetime(DateUtil.getNowDate());
            entity.setCreateuser(userInfo.getUserId());
            entity.setFirstversion(mainId);
            entity.setIsmain(1);
            entity.setUpdatetime(null);
            entity.setUpdateuser(null);
            entity.setId(mainId);
        } else {
            entity.setUpdatetime(DateUtil.getNowDate());
            entity.setUpdateuser(userInfo.getUserId());
        }
        this.saveOrUpdate(entity);

        //ThemeTree子表数据新增修改
        if (!isSave) {
            QueryWrapper<ThemeTreeEntity> ThemeTreequeryWrapper = new QueryWrapper<>();
            ThemeTreequeryWrapper.lambda().eq(ThemeTreeEntity::getThemeid, entity.getId());
            themeTreeService.remove(ThemeTreequeryWrapper);
        }
        if (themeForm.getThemeTreeList() != null) {
            List<ThemeTreeEntity> tableField116 = JsonUtil.getJsonToList(themeForm.getThemeTreeList(), ThemeTreeEntity.class);
            for (ThemeTreeEntity entitys : tableField116) {
                entitys.setId(RandomUtil.uuId());
                entitys.setThemeid(entity.getId());
                if (isSave) {
                } else {
                }
                themeTreeService.saveOrUpdate(entitys);
            }
        }
    }

    @Override
    public List<TreeVO> getThemeTree(String id, String isPublish, boolean addPrefix) {
        ThemeEntity info = this.getInfo(id);
        String themename = info.getThemename();

        List<ThemeTreeEntity> themeTreeList = getThemeTreeList(id,isPublish);
        if (themeTreeList.isEmpty()) {
            // 添加顶级节点
            TreeVO rootNode = new TreeVO();
            rootNode.setId("0");
            rootNode.setLabel(themename);
            rootNode.setChildren(new ArrayList<>());
            rootNode.setParentId(null);
            rootNode.setSort(BigDecimal.valueOf(0));
            rootNode.setDes("");
            rootNode.setThemeId(id);

            List<TreeVO> result = new ArrayList<>();
            result.add(rootNode);
            if (addPrefix) {
                addLevelNumbers(result, "");
            }
            return result;
        }
        List<TreeVO> treeDTOList = new ArrayList<>();
        Map<String, TreeVO> dtoMap = new HashMap<>();

        for (ThemeTreeEntity entity : themeTreeList) {
            TreeVO dto = new TreeVO();
            dto.setId(entity.getId());
            dto.setLabel(entity.getName());
            dto.setParentId(entity.getPid());
            dto.setSort(entity.getSort());
            dto.setDes(entity.getDes());
            dto.setThemeId(id);
            dto.setChildren(new ArrayList<>());
            dtoMap.put(entity.getId(), dto);
        }

        // 构建树结构
        for (TreeVO dto : dtoMap.values()) {
            String parentId = dto.getParentId();
            if (parentId == null || !dtoMap.containsKey(parentId)) {
                treeDTOList.add(dto);
            } else {
                TreeVO parent = dtoMap.get(parentId);
                parent.getChildren().add(dto);
            }
        }

        // 对每个节点的子节点进行排序
        for (TreeVO dto : dtoMap.values()) {
            if (dto.getChildren() != null && !dto.getChildren().isEmpty()) {
                dto.getChildren().sort((a, b) -> {
                    if (a.getSort() == null) return 1;
                    if (b.getSort() == null) return -1;
                    return a.getSort().compareTo(b.getSort());
                });
            }
        }

        // 添加顶级节点
        TreeVO rootNode = new TreeVO();
        rootNode.setId("0");
        rootNode.setLabel(themename);
        rootNode.setChildren(treeDTOList);
        rootNode.setParentId(null);
        rootNode.setSort(BigDecimal.valueOf(0));
        rootNode.setDes("");
        rootNode.setStatus(info.getThemestatus());
        rootNode.setThemeId(id);

        List<TreeVO> result = new ArrayList<>();
        result.add(rootNode);

        if (addPrefix) {
            addLevelNumbers(result, "");
        }

        return result;
    }

    @Override
    public ActionResult updateStatus(ThemeEntity entity, String status) {
        if (entity == null) {
            return ActionResult.fail("主题不存在");
        }

        // 验证状态码是否合法
        if (!Arrays.asList("0", "1", "2").contains(status)) {
            return ActionResult.fail("不支持的状态值");
        }

        try {
            entity.setThemestatus(status);
            this.updateById(entity);

            String statusName = "";
            switch (status) {
                case "0":
                    statusName = "草稿";
                    break;
                case "1":
                    statusName = "启用";
                    break;
                case "2":
                    statusName = "停用";
                    break;
            }

            return ActionResult.success("状态已更新为" + statusName);
        } catch (Exception e) {
            log.error("更改主题状态失败", e);
            return ActionResult.fail("状态更新失败");
        }
    }

    /**
     * 添加层级编号
     */
    private void addLevelNumbers(List<TreeVO> nodes, String parentNumber) {
        for (int i = 0; i < nodes.size(); i++) {
            TreeVO node = nodes.get(i);
            String currentNumber = parentNumber.isEmpty() ? String.valueOf(i + 1) : parentNumber + "." + (i + 1);
            node.setLabel(currentNumber + " " + node.getLabel());
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                addLevelNumbers(node.getChildren(), currentNumber);
            }
        }
    }


    @Override
    public ActionResult<MyPageListVO<ThemeEntity>> getThemeVersionList(ThemeQueryReq pagination) {
        // 构建查询条件
        QueryWrapper<ThemeEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotBlank(pagination.getName())) {
            queryWrapper.like("THEMENAME", pagination.getName());
        }
        if (StringUtil.isNotBlank(pagination.getVersion())) {
            queryWrapper.like("VERSION", pagination.getVersion());
        }
        if (StringUtil.isNotNull(pagination.getIsMain())) {
            queryWrapper.eq("ISMAIN", pagination.getIsMain());
        }
        if (StringUtil.isNotNull(pagination.getThemeId())) {
            ThemeEntity theme = this.getById(pagination.getThemeId());
            if (theme != null && StringUtil.isNotEmpty(theme.getFirstversion())) {
                queryWrapper.eq("firstVersion", theme.getFirstversion());
            }
        }
        queryWrapper.isNotNull("VERSION");

        // 处理分页
        long current = pagination.getCurrentPage() != null ? pagination.getCurrentPage() : 1;
        long size = pagination.getPageSize() != null ? pagination.getPageSize() : 9999;

        Page<ThemeEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<ThemeEntity> themeEntityPage = this.page(page, queryWrapper);

        List<ThemeEntity> records = themeEntityPage.getRecords();
        List<String> userIds = records.stream().map(ThemeEntity::getBelonguser).filter(StringUtil::isNotEmpty).distinct().collect(Collectors.toList());

        if (!userIds.isEmpty()) {
            Map<String, String> userMap = userService.listByIds(userIds).stream().collect(Collectors.toMap(UserEntity::getId, UserEntity::getRealName, (oldValue, newValue) -> oldValue));

            records.forEach(entity -> {
                String realName = userMap.get(entity.getBelonguser());
                if (realName != null) {
                    entity.setBelonguser(realName);
                }
            });
        }

        // 构建返回结果
        MyPageListVO<ThemeEntity> result = new MyPageListVO<>();
        result.setList(themeEntityPage.getRecords());
        result.setPagination(new MyPageInfo(themeEntityPage.getTotal(), current, size, pagination.getIsAll()));

        return ActionResult.success(result);
    }

    @Override
    public ActionResult<ThemeVersionInfoResp> getThemeVersionInfo(String themeId) {
        List<TreeVO> themeTree = this.getThemeTree(themeId, "1",true);

        // 先检查主题 ID 是否为空
        if (StringUtil.isEmpty(themeId)) {
            return ActionResult.fail("主题 ID 不能为空");
        }

        // 获取主题信息
        ThemeEntity themeEntity = this.getInfo(themeId);
        if (themeEntity == null) {
            return ActionResult.fail("未找到指定主题信息");
        }

        ThemeVersionInfoResp resp = new ThemeVersionInfoResp();
        resp.setName(themeEntity.getThemename());
        resp.setVersion(themeEntity.getVersion());
        resp.setTreeVOList(themeTree);

        String userId = themeEntity.getBelonguser();
        if (userId != null) {
            UserEntity userEntity = userService.getById(userId);
            if (userEntity != null) {
                String realName = userEntity.getRealName();
                resp.setBelongUser(realName);
            }
        }

        return ActionResult.success(resp);
    }

    @Override
    @Transactional
    public ActionResult setMainVersion(String themeId) {
        try {
            ThemeEntity one = this.getInfo(themeId);
            if (one == null) {
                return ActionResult.fail("未找到这个主题");
            } else {
                // 先将 firstVersion 相同的所有主题版本的 ismain 字段设置为 0
                String firstVersion = one.getFirstversion();
                ThemeEntity updateEntity = new ThemeEntity();
                updateEntity.setIsmain(0);
                QueryWrapper<ThemeEntity> firstVersionWrapper = new QueryWrapper<>();
                firstVersionWrapper.lambda().eq(ThemeEntity::getFirstversion, firstVersion);
                this.update(updateEntity, firstVersionWrapper);

                // 再将指定主题版本的 ismain 字段设置为 1
                ThemeEntity targetEntity = this.getById(themeId);
                if (targetEntity == null) {
                    return ActionResult.fail("未找到指定的主题版本");
                }
                targetEntity.setIsmain(1);
                boolean updateResult = this.updateById(targetEntity);

                if (updateResult) {
                    return ActionResult.success("设置主版本成功");
                } else {
                    return ActionResult.fail("设置主版本失败");
                }
            }
        } catch (Exception e) {
            log.error("设置主版本时发生异常", e);
            return ActionResult.fail("设置主版本时发生异常: " + e.getMessage());
        }
    }

    public ActionResult<List<ThemePkDTO>> getPkData() {
        List<ThemeEntity> themeList = this.lambdaQuery()
                .select(ThemeEntity::getId,
                        ThemeEntity::getThemename,
                        ThemeEntity::getVersion,
                        ThemeEntity::getFirstversion,
                        ThemeEntity::getIsmain)
                .isNotNull(ThemeEntity::getVersion)
                .list();

        List<ThemePkDTO> result = themeList.stream().map(theme -> {
            ThemePkDTO data = new ThemePkDTO();
            data.id = theme.getId();
            data.firstId = theme.getFirstversion();
            data.themeName = theme.getThemename();
            data.themeVersion = theme.getVersion();
            data.isMain = theme.getIsmain();
            return data;
        }).collect(Collectors.toList());

        return ActionResult.success(result);
    }

    @Override
    public ActionResult<ArrayList<ThemePkDataDTO> > getThemeVersion(List<ThemePkDataDTO> themeIds) {
        if (themeIds == null || themeIds.isEmpty()) {
            return ActionResult.fail("主题ID列表不能为空");
        }
        ArrayList<ThemePkDataDTO> themePkDataDTOS=new ArrayList<>();

        for (ThemePkDataDTO item : themeIds) {
            ThemePkDataDTO themePkDataDTO = new ThemePkDataDTO();
            themePkDataDTO.setId(item.getId());
            themePkDataDTO.setVersion(item.getVersion());
            //处理treeData
            List<TreeVO> themeTree = this.getThemeTree(item.getId(), "1",true);
            // 添加层级编号
//            addLevelNumbers(themeTree, "");
            // 构建带编号的字符串
            StringBuilder numberedString = new StringBuilder();
            buildNumberedString(themeTree, numberedString);
            themePkDataDTO.setTreeData(numberedString.toString());
            themePkDataDTOS.add(themePkDataDTO);
        }

        return ActionResult.success(themePkDataDTOS);
    }

    @Override
    public List<TreeVO> getMergedThemeTree(List<String> ids, String isPublish) {
        // 创建一个Map来存储所有树的节点
        Map<String, TreeVO> allNodes = new HashMap<>();

        // 遍历每个ID，获取对应的树结构
        for (String id : ids) {
            List<TreeVO> tree = getThemeTree(id, isPublish,false);

            // 为每个节点生成唯一ID并添加到Map中
            for (TreeVO node : tree) {
                String uniqueId = UUID.randomUUID().toString();
                node.setId(uniqueId); // 设置唯一ID
                node.setUniqueId(node.getId());
                allNodes.put(uniqueId, node);
            }
        }

        // 构建合并后的树结构
        List<TreeVO> mergedTree = new ArrayList<>();
        for (TreeVO node : allNodes.values()) {
            if (node.getParentId() == null || node.getParentId().equals("0")) {
                // 顶级节点
                mergedTree.add(node);
            } else {
                // 找到父节点并添加到其子节点列表
                TreeVO parent = allNodes.get(node.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(node);
                }
            }
        }

        return mergedTree;
    }


    private void buildNumberedString(List<TreeVO> nodes, StringBuilder builder) {
        for (TreeVO node : nodes) {
            builder.append(node.getLabel()).append("\n");
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                buildNumberedString(node.getChildren(), builder);
            }
        }
    }
}
